package com.javabi.unix.parser.free;

import com.javabi.unix.line.LineNumberProcessor;
import com.javabi.unix.line.LineTokenizer;

public class FreeParser extends LineNumberProcessor<Free> {

	private Free free = null;

	@Override
	public Free getResult() {
		if (free == null) {
			throw new IllegalStateException("free not set");
		}
		return free;
	}

	@Override
	public boolean processLine(String line, int number) {
		if (number == 1) {
			parseColumnNames(line);
		}
		if (number == 2) {
			parserMem(line);
		}
		return true;
	}

	private void parserMem(String line) {

		// Parse the mem row
		LineTokenizer tokenizer = new LineTokenizer(line);
		tokenizer.skip("Mem:");
		
		Free mem = new Free();
		mem.setTotal(tokenizer.nextLong());
		mem.setUsed(tokenizer.nextLong());
		mem.setFree(tokenizer.nextLong());
		mem.setShared(tokenizer.nextLong());
		mem.setBuffers(tokenizer.nextLong());
		mem.setCached(tokenizer.nextLong());
		this.free = mem;

	}

	private void parseColumnNames(String line) {

		// This just verifies that the column names exist as expected
		LineTokenizer tokenizer = new LineTokenizer(line);
		tokenizer.skip("total");
		tokenizer.skip("used");
		tokenizer.skip("free");
		tokenizer.skip("shared");
		tokenizer.skip("buffers");
		tokenizer.skip("cached");
	}

}
